"""
视频管理器
整合AI视频生成和剪映导入功能
"""

import asyncio
import logging
from pathlib import Path
from typing import Optional

from .ai_video_generator import AIVideoGenerator
from .jianying_integration import JianYingIntegration


class VideoManager:
    """视频管理器"""
    
    def __init__(self, config_path: str = "config.yaml"):
        """
        初始化视频管理器
        
        Args:
            config_path: 配置文件路径
        """
        self.config_path = config_path
        self.logger = logging.getLogger(__name__)
        
        # 初始化组件
        self.ai_generator = AIVideoGenerator(config_path)
        self.jianying_integration = JianYingIntegration(config_path)
    
    async def generate_and_import(self, text: str, project_name: Optional[str] = None) -> dict:
        """
        生成AI视频并导入剪映
        
        Args:
            text: 视频文案
            project_name: 剪映项目名称
            
        Returns:
            包含结果信息的字典
        """
        self.logger.info("开始AI视频生成与剪映导入流程")
        
        try:
            # 生成AI视频
            async with self.ai_generator as generator:
                video_path = await generator.generate_video(text)
            
            self.logger.info(f"AI视频生成成功: {video_path}")
            
            # 导入到剪映
            draft_path = self.jianying_integration.import_to_jianying(video_path, project_name)
            
            result = {
                'success': True,
                'video_path': video_path,
                'draft_path': draft_path,
                'message': '视频生成并导入剪映成功'
            }
            
            self.logger.info("流程完成")
            return result
            
        except Exception as e:
            self.logger.error(f"流程失败: {e}")
            return {
                'success': False,
                'error': str(e),
                'message': '视频生成或导入失败'
            }
    
    def generate_and_import_sync(self, text: str, project_name: Optional[str] = None) -> dict:
        """
        同步版本的生成和导入功能
        
        Args:
            text: 视频文案
            project_name: 剪映项目名称
            
        Returns:
            包含结果信息的字典
        """
        async def _run():
            return await self.generate_and_import(text, project_name)
        
        return asyncio.run(_run())
    
    def list_jianying_drafts(self) -> list:
        """列出剪映草稿项目"""
        return self.jianying_integration.list_drafts()
    
    def cleanup_temp_files(self):
        """清理临时文件"""
        import shutil
        
        temp_dir = Path(self.jianying_integration.config['paths']['temp_dir'])
        if temp_dir.exists():
            shutil.rmtree(temp_dir)
            self.logger.info("临时文件清理完成")
        
        # 重新创建空目录
        temp_dir.mkdir(exist_ok=True)